<!-- 后结算模块-财务管理-销售管理-销售单详情 -->
<template>
  <div class="auth-product distributor-settlement-box">
    <el-container class="partDetails is-vertical">
      <tabs
        :tabs-arr="tabSliceList"
        @returnIndex="tabsHandle" />
      <record-info
        class="custom-info"
        :record-form="saleCommonForm"
        :record-data="headerInfo">
        <template slot="recordInfoslot">
          <div
            class="solt-info"
            v-if="activeIndex === 0">
            <span class="left-span">
              销售产品总数
              <span class="right-span">{{ headerInfo.prodTotalCount }}</span>
            </span>
            <span>
              品种数
              <span>{{ headerInfo.prodTypeCount }}</span>
            </span>
            <span>
              金额合计 （元）:
              <span>
                <span class="price">{{ headerInfo.orderAmount | getFormatterPrice }}</span>
              </span>
            </span>
          </div>
          <div
            class="solt-info"
            v-if="activeIndex === 1">
            <span class="left-span">
              发货单号
              <span class="right-span">{{ headerInfo.deliverCode }}</span>
            </span>
            <span>
              发货时间
              <span class="right-span">{{ headerInfo.deliverTime }}</span>
            </span>
            <span>
              发货人
              <span class="right-span">{{ headerInfo.deliverer }}</span>
            </span>
          </div>
          <div
            class="solt-info"
            v-if="activeIndex === 1">
            <span class="left-span">
              发货产品总数
              <span>{{ headerInfo.deliverCount }}</span>
            </span>
            <span>
              品种数
              <span>{{ headerInfo.deliverTypeCount }}</span>
            </span>
            <span>
              金额合计 （元）
              <span class="price">{{ headerInfo.deliverTotalAmount | getFormatterPrice }}</span>
            </span>
          </div>
        </template>
      </record-info>
      <el-editable
        class="distributor-edit-box"
        :data="activeList"
        :key="activeIndex"
        height="400"
        v-loading="tableLoading"
        :columns="activeColumns"
      >
        <template
          slot="default-pssRegistrationNumber"
          slot-scope="scope">
          <el-button
            :disabled="!scope.row.pssRegistrationNumber||!scope.row.pssRegistrationId"
            v-html="regisNoButton(scope.row, 'pssRegistration')"
            @click="showPdfRegistion(scope.row.pssRegistrationId)"
            type="text"
          />
        </template>
        <template
          slot="default-hspRegistrationNumber"
          slot-scope="scope">
          <el-button
            :disabled="!scope.row.hspRegistrationNumber||!scope.row.hspRegistrationId"
            v-html="regisNoButton(scope.row, 'hspRegistration')"
            @click="showPdfRegistion(scope.row.hspRegistrationId)"
            type="text"
          />
        </template>
        <!-- 查看发票详情 -->
        <template
          slot="default-invoiceAction"
          slot-scope="scope">
          <el-button
            @click="toLookDetails(scope.row)"
            type="text"
          >查看详情</el-button>
        </template>
        <!-- 发票影像(记得使用UI给的小图标) -->
        <template
          slot="default-invoiceUrl"
          slot-scope="scope">
          <div style="display:flex; justify-content: center;">
            <el-image
              v-if="scope.row.invoiceUrl"
              @click="toLookDetails(scope.row)"
              style="width: 23px; height: 16.6px;"
              :src="imageicon"
            />
          </div>
        </template>
      </el-editable>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
    </el-container>
    <follow-goods
      :is-show-follow-goods-list="isShowFollowGoodsList"
      :follow-goods-list-data="FollowGoodsListData"
      :role-type="roleType"
      :settle="settle"
      @cancelDialog="cancelDialog"
    />
    <invoice-details
      :display-or-not="displayOrNotDetails"
      :invoice-url="activeInvoiceUrl"
      :invoice-no="activeInvoiceNo"
      @cancelDialog="cancelDialogInvoice" />
  </div>
</template>

<script>
import {
  detailTabsArr,
  statusArr,
  saleCommonForm,
  partOrderColumns,
  partDeliverColumns
} from './const'
import tabs from '@components/tabs/index.vue'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import RecordInfo from '@/moduleComponents/beforeSettle/distributorSide/purchasingManagement/record'
import { attrItemList } from '@const/orderCenterApi'
import {
  distributorSaleConfrim,
  distributorSaleDeliverDetail,
  distributorSaleList,
  distributorSaleOrderDetail,
  distributorSaleOrderOperate,
  distributorSaleCount,
  distributorSaleItemUpdate,
  distributorSaleWait,
  saleManagerPeerList
} from '@const/beforeSettleApi'
import ElEditable from '@components/el-editable'
import { cloneDeep, isObject, hasIn } from 'lodash'
import { getFormatterPrice } from '@const/filter'
import { getCertificate } from '@const/productCenterApiV2'
import followGoods from '@/moduleComponents/beforeSettle/followGoodsNote'
import invoiceDetails from '@/moduleComponents/beforeSettle/invoiceDetails/index.vue'
export default {
  components: { ElEditable, tabs, RecordInfo, followGoods, invoiceDetails },
  data () {
    return {
      imageicon: require('@assets/icon/beforeSettle/imageicon.png'),
      id: this.$route.query.id,
      orderStatus: null,
      // 表格Loading
      tableLoading: false,
      // 表单 详情展示内容-table
      columnsLists: [partOrderColumns, partDeliverColumns],
      orderLists: [],
      // 详情tab
      detailTabsArr,
      curPage: 1, // 当前页
      PAGE_NUMBER, // 页码数组
      PAGINATION_LAYOUT, // 页码功能布局
      pageSize: PAGE_NUMBER[0], // 一页的数量
      totalElements: 0, // 总共的条数
      activeIndex: 0,
      // 订单详情信息
      headerInfo: {},
      saleCommonForm,
      isShowFollowGoodsList: false,
      FollowGoodsListData: [],
      roleType: 2, // 登录角色（1-医院 2-配送商）
      settle: 2, // 1-结算前，2-结算后
      // 查看发票详情
      displayOrNotDetails: false,
      activeInvoiceUrl: '',
      activeInvoiceNo: ''
    }
  },

  mounted () {
    this.getList()
    this.initNavButtons()
  },
  filters: {
    getFormatterPrice
  },
  computed: {
    tabSliceList () {
      // 订单状态（0-全部，11-待响应，12-待发货，13-发货完成，14-已完成，15-已撤消，16-已拒绝）
      let detailTabsArr = cloneDeep(this.detailTabsArr)
      // 13,14-发货完成--可以查看收货信息
      if (![13, 14].includes(this.orderStatus)) {
        detailTabsArr[1].disabled = true
      }
      return detailTabsArr
    },
    activeList () {
      return this.orderLists[this.activeIndex]
    },
    activeColumns () {
      return this.columnsLists[this.activeIndex]
    }
  },
  methods: {
    // 初始化 导航栏 按钮组
    initNavButtons () {
      let arr = [
        { type: 'button', val: '返回', handle: this.back }
      ]
      if (Number(this.$route.query.orderStatus) === 13 || Number(this.$route.query.orderStatus) === 14) {
        arr.push({ type: 'primary', val: '查看随货同行单', handle: this.lookFollowGoodsNote })
      }
      const btn = {
        type: 'btn',
        arr: arr
      }
      this.$store.commit('changeLayoutHandle', btn)
    },
    // 查看发票详情
    toLookDetails (val) {
      this.activeInvoiceUrl = val.invoiceUrl
      this.activeInvoiceNo = val.invoiceNo
      this.displayOrNotDetails = true
    },
    cancelDialogInvoice () {
      this.activeInvoiceUrl = ''
      this.activeInvoiceNo = ''
      this.displayOrNotDetails = false
      this.getList()
    },
    // 查看随货同行单
    lookFollowGoodsNote () {
      this.$axios
        .$post(saleManagerPeerList, {
          purchaseOrderId: this.headerInfo.purchaseOrderId,
          saleOrderId: this.headerInfo.saleOrderId,
          roleType: this.roleType // 登录角色（1-医院 2-配送商)
        })
        .then(res => {
          let data = res.payload || []
          // 如果有多个随货同行单，就弹框让其选择
          // 如果只有一个，直接弹出
          if (data.length > 0) {
            this.FollowGoodsListData = data
            this.isShowFollowGoodsList = true
          } else {
            this.$message({
              type: 'warning',
              message: '此订单还没有随货同行单！'
            })
          }
        })
    },
    cancelDialog () {
      this.isShowFollowGoodsList = false
    },
    // 返回上一级
    back () {
      this.$router.go(-1)
    },
    /**
     * @param [Number] index
     * @desc 通过index选择请求方法 -- 获取--0:订单信息/1:收货信息
     */
    async getList (index = this.activeIndex) {
      this.tableLoading = true
      // 表格字段名称 订单详情--getOrderList 发货详情--getDeliverList
      const requestList = [this.getOrderList, this.getDeliverList]
      const request = requestList[index]
      const { infoList, ...baseInfo } = await request()
      Object.keys(baseInfo).forEach(key => {
        if (key === 'orderStatus') {
          this.orderStatus = baseInfo[key]
          baseInfo[key] = statusArr[baseInfo[key]]
        }
        this.$set(this.headerInfo, key, baseInfo[key] || '--')
      })
      this.$set(this.orderLists, index, infoList.content)
      this.totalElements = infoList.totalElements || 0
      this.tableLoading = false
    },
    // 详情-销售单详情
    async getOrderList () {
      // 表格字段名称 订单详情--saleProductList 发货详情--deliverProductList
      const url = distributorSaleOrderDetail
      const data = {
        page: this.curPage,
        pageSize: this.pageSize,
        saleOrderId: this.id
      }
      const res = await this.$axios.$post(url, data)
      const { saleProductList, ...baseInfo } = res.payload
      return { ...baseInfo, infoList: saleProductList }
    },
    // 详情-发货详情
    async getDeliverList () {
      const url = distributorSaleDeliverDetail
      const data = {
        page: this.curPage,
        pageSize: this.pageSize,
        saleOrderId: this.id
      }
      const res = await this.$axios.$post(url, data)
      const { deliverProductList, ...baseInfo } = res.payload
      return { ...baseInfo, infoList: deliverProductList }
    },
    showPdfRegistion (id) {
      this.$axios({
        method: 'get',
        url: getCertificate,
        params: {
          id: id
        }
      }).then(res => {
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        // let url = obj.licenseUrl
        let url = obj.pictureUrl
        if (!url) {
          this.$message({
            type: 'warning',
            message: '获取失败，请在产品管理中维护该产品的注册证信息'
          })
        } else {
          this.$pdfViewer({ url, title: '注册证pdf预览' })
        }
      })
    },
    // tab切换
    tabsHandle (index) {
      this.activeIndex = index
      this.curPage = 1
      this.pageSize = PAGE_NUMBER[0]
      this.getList()
    },
    regisNoButton (data, str = 'registration') {
      const number = `${str}Number`
      const id = `${str}Id`
      if (data[number]) {
        return data[number]
      } else if (!data[number] && data[id]) {
        return '暂无注册证号'
      } else if (!data[number] && !data[id]) {
        return '暂无数据'
      }
    },
    // 页码更改
    handleSizeChange (size) {
      this.pageSize = size
      this.getList()
    },

    // 切换不一样的页面,重置一切数据
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.getList()
    }
  }
}
</script>

<style lang="less">
.distributor-settlement-box {
  .partDetails {
    height: 100%;
    .custom-info {
      margin: 0 0 20px 0;
    }
    .pagination {
      padding-top: 10px;
      display: flex;
      justify-content: flex-end;
      padding-right: 0;
    }
  }
}
</style>
